var User = function () {

    this.$grid_selector = $("#user-grid-table");
    this.pager_selector = "#user-grid-pager";

    this.URL = {
        // 编辑用户
        USER_EDIT: '/member/user/{{id}}',
        CHANGE_PASSWORD: '/member/user/password/change',
        // 获取全部角色
        ROLE_GET: '/member/role/user/{{id}}'
    };

    this.colModel = [
        {name: 'id', index: 'id', hidden: true, key: true, width: 50, editable: true},
        {
            name: 'username',
            index: 'username',
            width: 80,
            editable: true,
            editrules: {required: true, edithidden: true},
            editoptions: {
                size: "20", maxlength: "30"
            },
            formoptions: {}
        }, {
            name: 'loginName',
            index: 'loginName',
            width: 80,
            editable: true,
            editoptions: {size: "20", maxlength: "30"},
            editrules: {required: true}
        },
        {
            name: 'email',
            index: 'email',
            editable: true,
            formatter: 'email',
            editrules: {
                required: true,
                email: true
            }
        },
        {
            name: 'mobile',
            index: 'mobile',
            width: 50,
            editable: true
        },
        {
            name: 'roles',
            index: 'roles',
            hidden: true,
            width: 50
        },
        {
            name: 'status',
            index: 'status',
            width: 70,
            sortable: false,
            editable: true,
            edittype: "checkbox",
            editoptions: {value: "10:11", defaultValue: '10'},
            editrules: {required: true},
            formatter: function (cellValue) {
                if (cellValue === '10' || cellValue === 10)
                    return '开启';
                else
                    return '关闭';
            },
            unformat: function (cellValue) {
                if (cellValue === '开启')
                    return '10';
                else
                    return '11';
            }
        },
        {
            name: 'createdAt',
            index: 'createdAt',
            width: 100,
            formatter: "date",
            formatoptions: {srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d H:i:s'}
        }
    ];
    this.options = {
        moduleKey: 'member/user',
        pager: this.pager_selector,
        sortname: 'createdAt',
        sortorder: 'desc',
        caption: "模块列表",
        colNames: ['ID', '用户名', '登录名', '邮箱', '手机', '角色', '状态', '创建时间'],
        colModel: this.colModel,
        navbarDefaultIcon: {
            add: false
        }
    };

    // 密码修改表单
    this.passwordFormTemplate = _.template("<form id='password_change' class='form-horizontal' style='padding: 12px;' action='{{action}}' method='post'>\
                            <input type='hidden' id='id' name='id' value='{{id}}'>\
                            <div class='form-group'>\
                                <label class='col-sm-4'>&nbsp;&nbsp;&nbsp;&nbsp;用户名：</label>\
                                <div class='col-sm-8'>\
                                {{username}}\
                                </div>\
                            </div>\
                            <div class='form-group'>\
                                <label class='col-sm-4' for='password'>&nbsp;&nbsp;&nbsp;&nbsp;新密码：</label>\
                                <div class='col-sm-8'>\
                                    <input autocomplete='false' class='form-control' id='password' name='password' type='password'>\
                                </div>\
                            </div>\
                            <div class='form-group'>\
                                <label class='col-sm-4' for='confirm'>重复密码：</label>\
                                <div class='col-sm-8'>\
                                    <input autocomplete='false' class='form-control' name='confirm' id='confirm' type='password'>\
                                </div>\
                            </div>\
                        </form>");

    this.roleSettingTemplate = '<div style="padding: 0 12px 0 12px;"><select multiple="multiple" size="10" id="role_dual_list"></select></div>'
};

User.prototype = {
    // 初始化表格
    initGird: function () {

        var self = this;
        this.$grid_selector.xumf_jqGird(this.options);
        this.$grid_selector
            .xumf_jqGird('navGrid', this.pager_selector).jqGrid('navSeparatorAdd', this.pager_selector)
        // 修改密码按钮初始化
            .xumf_jqGird('navGrid', this.pager_selector).jqGrid('navButtonAdd', this.pager_selector,
            {
                caption: '',
                title: "修改密码",
                buttonicon: "fa fa-key",
                onClickButton: function () {
                    $(this).getGridSelectedRow(function (rowData) {
                        self.passwordChange(rowData);
                    });
                }
            })
        // 编辑角色按钮初始化
            .xumf_jqGird('navGrid', this.pager_selector).jqGrid('navButtonAdd', this.pager_selector,
            {
                caption: '',
                title: "设置角色",
                buttonicon: "fa fa-users",
                onClickButton: function () {
                    var rowId = $(this).xumf_jqGird('getGridParam', 'selrow');
                    if (null === rowId) {
                        $.xumf.gritterError('请选择行');
                    } else {
                        var rowData = $(this).xumf_jqGird('getRowData', rowId);
                        self.roleSetting(rowData);
                    }
                }
            });
    },
    /**
     * 角色设置弹框
     */
    roleSetting: function (rowData) {

        var self = this;
        // 显示弹框
        layer.open({
            title: '设置角色',
            area: ['60%', '55%'],
            content: this.roleSettingTemplate,
            yes: function (index, layero) {
                self.roleSettingAction(rowData, index);
            },
            success: function (index, layero) {
                self.initSelectRole(rowData);
            }
        });
    },
    roleSettingAction: function (rowData, index) {
        var self = this;
        var roleIdAry = $('#role_dual_list').val();
        var roleIds = roleIdAry ? roleIdAry.join(',') : '';
        $.xumf.ajaxAndLoading({
            type: 'PUT',
            url: _.template(self.URL.USER_EDIT)({id: rowData.id}),
            data: {id: rowData.id, roles: roleIds}
        }).success(function (res) {
            res.success && layer.close(index);
            $.xumf.gritter(res);
            rowData.roles = roleIds;
            // 更新选择中行数据
            self.$grid_selector.jqGrid('setRowData', rowData.id, rowData);
        });
    },
    /**
     * 初始化角色选择框
     * @param rowData 当前选择行数据
     */
    initSelectRole: function (rowData) {
        $('#role_dual_list').xumf_select({
            url: _.template(this.URL.ROLE_GET)({id: rowData.id})
        }).on('xumf.select.success', function (e) {
            $(e.currentTarget).xumf_dual_list();
        })
    },
    /**
     * 密码修改弹框
     * @param rowData 一行的数据
     */
    passwordChange: function (rowData) {

        // 插入数据
        rowData.action = this.URL.CHANGE_PASSWORD;
        var template = this.passwordFormTemplate(rowData);
        // 显示弹框
        layer.open({
            title: '修改密码',
            content: template,
            yes: this.changeAction
        });
    },
    /**
     * 表单操作
     * @param index 当前层索引参数
     * @param layero 当前层的DOM对象
     */
    changeAction: function (index, layero) {
        var $form = $('#password_change');
        $form.validate({
            rules: {
                id: {required: true},
                password: {required: true, minlength: 6, maxlength: 100},
                confirm: {equalTo: '#password'}
            },
            messages: {confirm: {equalTo: '密码不一致'}},
            errorElement: "em"
        });
        // 验证成功
        if ($form.valid()) {
            $form.ajaxSubmit({
                success: function (res) {
                    layer.close(index);
                    $.xumf.gritter(res);
                }
            });
        }
    }
};